﻿using MySql.Data.MySqlClient;
using NB.MGJ.Common;
using NB.MGJ.Common.Helper;
using NB.MGJ.FrameWork;
using NB.MGJ.Model;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NB.MGJ.Service.Market
{
    public class MarketingUserService
    {
        public BaseRepository _baseRepository = new BaseRepository();
        DBHService _dbhservice = new DBHService();
        DBHService dbh = new DBHService();
        //注意，这里的骚操作直接是 库名.表名,万一以后如果是把库分服务器了，就不能这样写了

        #region 创建表
        /// <summary>
        /// 创建用户表
        /// </summary>
        /// <param name="tableName"></param>
        public void CreateUserTable(string tableName)
        {
            string createSql = string.Format(@"     
                 use  marketing;
                CREATE TABLE `{0}` (
                  `ID` int(11) NOT NULL   primary key auto_increment,
                  `OpenID` varchar(50) DEFAULT NULL,
                  `Nickname` varchar(200) DEFAULT NULL,
                  `Sex` int(1) DEFAULT NULL,
                  `Country` varchar(50) DEFAULT NULL,
                  `Provnice` varchar(50) DEFAULT NULL,
                  `City` varchar(50) DEFAULT NULL,
                  `Language` varchar(50) DEFAULT NULL,
                  `HeadImgUrl` longtext,
                  `OA_Time` dateTime DEFAULT  NULL  ,
                  `UnionId` int(11) DEFAULT NULL,
                  `GroupID` int(11) DEFAULT NULL,
                  `Phone` varchar(50) DEFAULT NULL,
                  `Name` varchar(50) DEFAULT NULL,
                  `CreateTime` dateTime DEFAULT NULL
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;", tableName);
            _baseRepository.ExecuteSql<int>(createSql);
        }

        #endregion


        /// <summary>
        /// 判断表是否存在  存在插入数据  不存在创建 在添加数据
        /// </summary>
        /// <param name="model">微信扫码返回的实体</param>
        /// <param name="Code">code码</param>
        /// <returns></returns>
        public int isInsert(OAuthUserInfo model, string eCode)
        {
            try
            {
                int result = 0;
                string tableName = "marketing.Marketing_User" + eCode;
                if (dbh.TabExists("marketing", "Marketing_User" + eCode))
                {
                    //数据是否存在  存在就更新下头像  不存在就添加  
                    if (_baseRepository.dataExists("select * from " + tableName + " where OpenID='" + model.openid + "'"))
                    {
                        result = UpdateReturnID(model, eCode);
                    }
                    else
                    {
                        result = InsertUser(model, eCode);
                    }
                }
                else
                {
                    CreateUserTable("Marketing_User" + eCode);
                    result = InsertUser(model, eCode);
                }
                return result;
            }
            catch (Exception ex)
            {
                WeiXinHelper.WriteLog("isInsertErr", ex.ToString());
                throw;
            }

        }

        #region 新增
        /// <summary>
        /// 添加方法（通过传递实体类添加数据，把添加的数据赋值给实体类属性，不添加的值不填写）
        /// </summary>
        /// <param name="UserModel">User0001Model实体类</param>
        /// <returns>int 0为失败 ；1为成功</returns>
        public int InsertUser(OAuthUserInfo model, string Ecode)
        {
            StringBuilder strSql = new StringBuilder();
            try
            {
                
                strSql.Append("insert into marketing.Marketing_User" + Ecode + " (");
                strSql.Append("OpenID,nickname,Sex,Country,Provnice,City,Language,HeadImgUrl,OA_Time,UnionId,GroupID,Phone,Name ) ");
                strSql.Append(" values (");
                strSql.Append("@OpenID,@nickname,@Sex,@Country,@Provnice,@City,@Language,@HeadImgUrl,@OA_Time,@UnionId,@GroupID ,@Phone,@Name);  ");
               
                MySqlParameter[] parameters = {
                    new MySqlParameter("@OpenID", model.openid),
                    //微信名可能有表情或者图标   所以需要base64加密处理
                    new MySqlParameter("@nickname",Base64Helper.Base64Encode( model.nickname)),   
                    new MySqlParameter("@Sex",model.sex),
                    new MySqlParameter("@Country", model.country),
                    new MySqlParameter("@Provnice", model.province),
                    new MySqlParameter("@City", model.city),
                    new MySqlParameter("@Language", ""),
                    new MySqlParameter("@HeadImgUrl",model.headimgurl ),
                    new MySqlParameter("@OA_Time",  DateTime.Now ),
                    new MySqlParameter("@UnionId", model.unionid),
                    new MySqlParameter("@GroupID",0),
                    new MySqlParameter("@Phone", ""),
                    new MySqlParameter("@Name", "")};

                return _baseRepository.ExecuteSqlRturnID(strSql.ToString(), parameters);
            }
            catch (Exception ex)
            {
                //WeiXinHelper.WriteLog("insertUserSql", strSql .ToString()+ ";@OpenID:" + model.openid + "@nickname" + model.nickname + "@Sex" + model.sex + "@Country" + model.country + "@Provnice" + model.province + "@City" + model.city + "@HeadImgUrl" + model.headimgurl + "@OA_Time" + DateTime.Now + "@UnionId" + model.unionid);
                //WeiXinHelper.WriteLog("insertUserErr",ex.ToString());
                throw;
            }
           

        }
        #endregion

        #region 更新用户信息 返回数据的ID
        public int UpdateReturnID(OAuthUserInfo model, string Ecode)
        {
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append(" update  marketing.Marketing_User" + Ecode + " set ");
                strSql.Append(" Nickname='" +Base64Helper.Base64Encode( model.nickname) + "',HeadImgUrl='" + model.headimgurl + "',OA_Time=now() ");
                strSql.Append(" where OpenID='" + model.openid + "' ; select id from marketing.Marketing_User" + Ecode + " where openID='" + model.openid + "'");
                WeiXinHelper.WriteLog("UpdateReturnID_SQL", strSql.ToString());
                return Convert.ToInt32(_baseRepository.GetSingle(strSql.ToString()));
            }
            catch (Exception ex)
            {
                WeiXinHelper.WriteLog("UpdateReturnID错误", ex.ToString());
                throw;
            }
        }
        #endregion

 
    }
}
